<?php
/**
 * 用户管理
 */
class UserApp extends CommonApp {
	
	private $roles;
	
	public function __construct(){
		$this->roles = $this->getRoles();
	}
	
	/**
	 * 列表页
	 */
	public function indexAct(){
		$where = '1 ';
		if(My::arr2var($_GET,'username')!='')
			$where .=  'AND `username` like "%'.I('get.username').'%" ';
		if(My::is_id(My::arr2var($_GET,'role_id')))
			$where .= "AND `role_id`=".$_GET['role_id']." ";
		$page = My::page(DB('user')->field('id')->where($where)->where($where)->count());
		$result = DB('user')->where($where)->where($where)->limit($page['limits'])->select();
		if(is_array($result)){
			foreach($result as &$value){
				//角色
				$value['role_id'] = isset($this->roles[$value['role_id']])?$this->roles[$value['role_id']]:0;
				//在线时长
				$value['online'] = DB('online')->where("uid='{$value['id']}'")->sum('length');
				$value['online'] = (isset($value['online']) AND $value['online'])?number_format($value['online'],1):0;
				//params
				$value['params'] = My::decodeJson($value['params']);
			}
		}
		$this->assign('roles', $this->roles);	
		$this->assign('result', $result);
		$this->assign('page', $page);
		$this->display();
	}
	
	/**
	 * 获取角色
	 */
	protected function getRoles(){
		if($roles = DB('role')->field('id,name')->select()){
			foreach($roles as $v){
				$data[$v['id']] = $v['name'];
			}
		}
		return $data;
	}

	/**
	 * 注册用户/编辑用户/修改密码
	 */
	public function saveAct(){
		//用户名
		$username = $_POST['username'] = My::arr2var($_POST,'username');
		//用户名的id
		$id = My::arr2var($_POST,'id');
		//username为空时
		if(empty($username) AND !My::is_id($id))
			$this->ajaxReturn(300, '用户名不能为空');
		//角色为空时
		if(!My::is_id(My::arr2var($_POST,'role_id')))
			$this->ajaxReturn(300, '角色不能为空!');
		//添加用户<注册>(id<=0 AND username!='')
		if(!My::is_id($id) AND !empty($username)){
			//通过username得到user表id
			$userid = self::username2userid($username);
			//开始注册(用户名,密码,邮箱)
			$reg_result = self::add2user(array("username"=>$username,'password'=>(My::arr2var($_POST,'password')!='')?My::arr2var($_POST,'password'):'123456','role_id'=>My::arr2var($_POST,'role_id'),'email'=>My::arr2var($_POST,'email')));//返回报错,或者新增user表数据的id
			//print_r($reg_result);exit;
			//注册结果
			if(My::is_id($reg_result)){
				$this->ajaxReturn(200,'注册新用户成功!!!');
			}else{
				$this->ajaxReturn(300,$reg_result);
			}
		}
		//编辑用户
		elseif(My::is_id($id)){
			//修改密码
			if(My::arr2var($_POST,'edit_password')==1){
				if(My::user('role_id')!=1){//超级管理员,无需验证旧密码
					if(!My::arr2var($_POST,'oldpassword')) $this->ajaxReturn(300, '旧密码不能为空!');
					$oldpassword = My::arr2var($_POST,'oldpassword');
					if(MD5(MD5($oldpassword))!=My::id2field('user',$id,'password'))
					    $this->ajaxReturn(300, '旧登录密码不正确!');
				}
				if(!My::arr2var($_POST,'newpassword1') OR !My::arr2var($_POST,'newpassword2')) $this->ajaxReturn(300, '新密码不能为空!');
				if(My::arr2var($_POST,'newpassword1')!=My::arr2var($_POST,'newpassword2')) $this->ajaxReturn(300, '两次输入的新密码不相同!');
				if(strlen(My::arr2var($_POST,'newpassword1'))<5)	$this->ajaxReturn(300, '密码长度不能小于5位');
				$_POST['password'] = md5(md5($_POST['newpassword1']));
			}
			//print_r($_POST);exit;
			//更新用户信息User表
			if(isset($_POST['params'])){
			    $params = My::id2field('user',$id,'params');
			    $_POST['params'] = $params ? array_merge($params,$_POST['params']) : $_POST['params'];
			}
			DB('user')->where("`id`= {$id}")->clear()->save($_POST);
			$this->ajaxReturn(200,'编辑成功!');
		}
	}

	/**
	 * 添加/修改:模板页面显示
	 */
	public function modifyAct(){
		//print_r($_SESSION);
		$id = I('request.id','');
		if(My::is_id($id)){
			$result = DB('user')->where("id={$id}")->find();
			if(!$result)
				$this->ajaxReturn(404,'数据不存在!');
			//params
			$result['params'] = My::decodeJson($result['params']);
			//user表中是否存在该用户
			$result['is_username'] = self::username2userid($result['username']);
			//assign
			$this->assign('result', $result);
		}
		//print_r($result);
		//表单模型
		$FORM = Form::item2FORM('user');
		$this->assign('FORM',$FORM);
		$this->assign('roles', $this->roles);
		$this->assign('boolean', array('1'=>'是','0'=>'否'));
		$this->display();
	}
	
	/**
	 * 删除用户
	 */
	public function deleteAct(){
		$idArr = My::arr2var($_REQUEST,'check_id');
		if(!$idArr)	$this->ajaxReturn(300, '编号错误');
		if(in_array(1, $idArr)){
			$this->ajaxReturn(300, '无法删除超级管理员角色');
		}
		$str = '';
		if(is_array($idArr))
		foreach($idArr as $value){
			$value = (int)$value;
			//$userid = DB('user')->where("id='{$value}'")->getField('id');
			$ok = DB('user')->where("id='{$value}'")->delete();
			if($ok){
				$str .= "删除成功! (ID={$value})<br>";
			}else
				$str .= "删除失败! (ID={$value})<br>";
		}
		$this->ajaxReturn(200, $str);
	}
	
	/**
	 * 修改密码
	 */
	public function setPwdAct(){
		$username = My::user('username'); 
		if(count($_POST) > 0){
			$old_password = md5(md5(My::arr2var($_POST,'old_password')));
			$new_password = My::arr2var($_POST,'new_password');
			$new_password2 = My::arr2var($_POST,'new_password2');
			
			$pwd_len = strlen($new_password);
			if($new_password != $new_password2){
				$this->ajaxReturn(300, '新密码跟确认密码不一致');
			}else if($pwd_len<6 || $pwd_len >8){
				$this->ajaxReturn(300, '密码长度必须限制在6~8位之间');
			}
			$manager_info = DB('user')->field('id')->where("username='{$username}' AND password='{$old_password}'")->find();
			if(!$manager_info){
				$this->ajaxReturn(300, '输入的旧密码错误');
			}else{
				DB('user')->where("id={$manager_info['id']}")->save(array('password'=>md5(md5($new_password))));
				$this->ajaxReturn(200, '密码修改成功');
			}
		}
		$this->assign('username', $username);
		$this->display();
	}
	
	
	/**
	 * 第三方登录解绑定
	 * @param int $_POST['id'] 用户id
	 * @param int $_POST['type'] 类型(qq、sina、weixin)
	 */
	public function unbindAct(){
	    $id = My::arr2var($_REQUEST,'id');
	    $type = My::arr2var($_REQUEST,'type');
	    if(!My::is_id($id))
	        $this->ajaxReturn(300,'ID有误!');
	    if(!in_array($type, array('qq','sina','weixin')))
	        $this->ajaxReturn(300,'类型有误!');
	    $oauth_type=C('oauth_type');
	    $ok = DB('user')->where("id={$id} AND openid_{$type} IS NOT NULL")->clear()->save(array("openid_{$type}"=>''));
	    if($ok>=0){
	        $this->ajaxReturn(200,"解除{$oauth_type[$type]}绑定成功!");
	    }else
	        $this->ajaxReturn(300,"解除{$oauth_type[$type]}绑定失败!");
	}

	/**
	 * 个人信息设置(修改密码)
	 */
	public function myinfoAct(){
		//POST
		if(My::arr2var($_POST,'Ttype')=='myinfo'){
			$username = My::user('username');
			$oldpassword = md5(md5(My::arr2var($_POST,'oldpassword')));
			if(DB('user')->where("`username`='{$username}' AND `password`='{$oldpassword}'")->count()>0){
				if(!My::arr2var($_POST,'newpassword1') OR !My::arr2var($_POST,'newpassword2')) $this->ajaxReturn(300, '新密码不能为空!');
				if(My::arr2var($_POST,'newpassword1')!=My::arr2var($_POST,'newpassword2')) $this->ajaxReturn(300, '两次输入的新密码不相同!');
				if(strlen(My::arr2var($_POST,'newpassword1'))<5)	$this->ajaxReturn(300, '密码长度不能小于5位');
				$password = md5(md5(My::arr2var($_POST,'newpassword1')));
				$ok = DB('user')->where("`username`='{$username}'")->save(array('password'=>$password));
				if($ok)
					$this->ajaxReturn(200,'修改密码成功!');
				else
					$this->ajaxReturn(300,'密码修改失败!');
			}else{
				$this->ajaxReturn(300,'旧密码不正确!');
			}
		}
		//show
		$userid = (int)My::user('userid');
		$result = DB('user')->where("id={$userid}")->find();
		if(isset($result['params']))
			$result['params'] = My::decodeJson($result['params']);
		$this->assign('result',$result);
		//print_r($result);
		$this->display();
	}

	
	/**
	 * 用户详情
	 * @params $_GET['id']
	 */
	public function detailAct(){
	    //id
	    $id = I('get.id',0);
	    $result = array();
	    if(My::is_id($id)){
	        //当前id用户数据
	        $result = My::id2detail("user",$id);
	        //角色
	        $result['role'] = isset($this->roles[$result['role_id']])?$this->roles[$result['role_id']]:0;
	        $this->assign('result',$result);
	    }
	    //display
	    $this->display();
	}
	
	
	/**
	 * 历史登录信息列表
	 */
	public function onlineAct(){
	    $id= My::arr2var($_REQUEST,'id');
	    if(!My::is_id($id))
	        $this->ajaxReturn(404,'ID有误!');
	    //search
	    $search = array();
	    $search['where'] = "1 ";
	    $search['where'] .= "AND `uid`='{$id}' ";
	    $search['field'] = "*";
	    $search['page'] = My::arr2var($_REQUEST,'page').(isset($_SESSION['pagesize'])?$_SESSION['pagesize']:'');//用于参与缓存标识
	    $result=My::getCache($search,array('pre'=>'online'));
	    if($result==''){
	        //page
	        $total = DB('online')->where($search['where'])->count();
	        $result['page'] = My::page($total);
	        //result
	        $result['data'] = DB('online')->field($search['field'])->where($search['where'])->order('adddate DESC,id DESC')->limit($result['page']['limits'])->select();
	        //echo DB('')->getLastSql();
	        //在线时长
	        $result['online'] = DB('online')->where("uid='{$id}'")->sum('length');
	        $result['online'] = (isset($result['online']) AND $result['online'])?number_format($result['online'],1):0;
	        //登录次数
	        $result['hit'] = DB('user')->where("id={$id}")->getField('hit');
	        My::setCache($search,$result,array('pre'=>'online'));
	    }
	    //计算时间距离
	    if(is_array($result['data']))
	        foreach($result['data'] as &$value){
	        $value['login'] = self::timeDiff($value['login_time']);
	        $value['logout'] = self::timeDiff($value['loginout_time']);
	    }
	    $this->assign('result',$result);
	    //print_r($result);
	    //display
	    $this->display();
	}
	
	private function timeDiff($time){
	    $now = time();
	    if(Date::dateDiff('M', $time, $now)>=6){
	        return '';
	    }elseif(Date::dateDiff('M', $time, $now)>=1){
	        return Date::dateDiff('M', $time, $now).'个月前';
	    }elseif(Date::dateDiff('D', $time, $now)>=1){
	        return Date::dateDiff('D', $time, $now).'天前';
	    }elseif(Date::dateDiff('H', $time, $now)>=1){
	        return Date::dateDiff('H', $time, $now).'小时前';
	    }elseif(Date::dateDiff('N', $time, $now)>=1){
	        return Date::dateDiff('N', $time, $now).'分钟前';
	    }else{
	        return Date::dateDiff('S', $time, $now).'秒前';
	    }
	}
	
	
	/**
	 * 添加一条数据到user用户表
	 * @param array $data[username] 用户名
	 * @param array $data[role_id] 角色ID
	 * @param array $data[password] 明文密码(可选项:默认123456)
	 * @param array $data[publish] 是否发布(可选项,默认123456)
	 */
	private function add2user($data=''){
	    if(empty($data['username']))
	        return "添用户失败(用户名不能为空)!";
	    if(DB('user')->where("`username`='{$data['username']}'")->count()>0)
	        return "添用户失败(系统用户表已存在该用户)!";
	    if(!My::is_id($data['role_id']))
	        return "添用户失败(角色id错误)!";
	    if(empty($data['password']))
	        $data['password'] = md5(md5("123456"));
	    else
	        $data['password'] = md5(md5($data['password']));
	    $data['login_ip'] = get_client_ip();
	    $data['register_time'] = date("Y-m-d H:i:s");
	    $data['publish'] = isset($data['publish'])?$data['publish']:1;
	    //print_r($data);exit;
	    //add
	    $ok = DB('user')->add($data);
	    //添加数据到user表成功
	    if($ok){
	        return $ok;
	    }
	    //添加数据到user表失败
	    else{
	        return "添用户失败!";
	    }
	}
	
	
	
	/**
	 * 用户名->user表的id <=只得到一个id>
	 * @param string username 用户名
	 * @return array id
	 */
	private function username2userid($username=''){
	    //用户为空时return
	    if(empty($username)) return false;
	    //得到user表id
	    $result = DB('user')->where("`username`='{$username}'")->cache()->getField('id');
	    return $result;
	}
}